package com.zbs.framework.common.weixin;

import com.alibaba.fastjson.JSONObject;
import com.zbs.framework.common.utils.OkHttpUtils;
import com.zbs.framework.common.weixin.entity.JsapiTicketResult;
import com.zbs.framework.common.weixin.entity.WxResult;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;

/**
 * @description: 微信授权
 * @author: Zbs
 * @create: 2020-10-12 18:00
 */
public class WxAuthorization {

    /**
     * 微信授权
     * @param code
     * @return
     */
    public static WxResult callback(String code) {
        //1 获取code值，临时票据，类似于验证码
        //2 拿着code请求 微信固定的地址，得到两个值 accsess_token 和 openid
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        //拼接三个参数 ：id  秘钥 和 code值
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstantWxUtils.appId,
                ConstantWxUtils.appSecret,
                code
        );
        //请求这个拼接好的地址，得到返回两个值 accsess_token 和 openid
        //使用httpclient发送请求，得到返回结果
        String accessTokenInfo = OkHttpUtils.get(accessTokenUrl);

        //从accessTokenInfo字符串获取出来两个值 accsess_token 和 openid
        //把accessTokenInfo字符串转换map集合，根据map里面key获取对应值
        //使用json转换工具 Gson
        JSONObject mapAccessToken = JSONObject.parseObject(accessTokenInfo);
        String access_token = mapAccessToken.getString("access_token");
        String openid = mapAccessToken.getString("openid");
        String refresh_token = mapAccessToken.getString("refresh_token");

        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=%s" +
                "&openid=%s" +
                "&lang=zh_CN";
        //拼接两个参数
        String userInfoUrl = String.format(
                baseUserInfoUrl,
                access_token,
                openid
        );
        //发送请求
        String userInfo = OkHttpUtils.get(userInfoUrl);
        //获取返回userinfo字符串扫描人信息
        JSONObject userInfoMap = JSONObject.parseObject(userInfo);
        String nickname = userInfoMap.getString("nickname");//昵称
        String headimgurl = userInfoMap.getString("headimgurl");//头像
        return new WxResult(access_token,openid,refresh_token,nickname,headimgurl);
    }

    public static String getTicket() {
        String baseAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=%s" +
                "&secret=%s";
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstantWxUtils.appId,
                ConstantWxUtils.appSecret
        );
        String accessTokenInfo = OkHttpUtils.get(accessTokenUrl);
        JSONObject mapAccessToken = JSONObject.parseObject(accessTokenInfo);
        String access_token = mapAccessToken.getString("access_token");

        String baserUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";
        String url = String.format(baserUrl, access_token);
        JSONObject hashMap = JSONObject.parseObject(OkHttpUtils.get(url));

        return hashMap.getString("ticket");
    }

    public static JsapiTicketResult sign(String url) {
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        String ticket = getTicket();
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes(StandardCharsets.UTF_8));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return new JsapiTicketResult(url,ticket,nonce_str,timestamp,signature);
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        //return UUID.randomUUID().toString();
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        //return Long.toString(System.currentTimeMillis() / 1000);
        return Long.toString(System.currentTimeMillis() / 1000);
    }


}
